<template>
  <div class="page">
    <el-row style="height: 100%">
      <el-col :span="4" style="height: 100%">
        <el-scrollbar style="height: 100%">
          <div class="components-list">
            <!-- 可使用组件 -->
            <div v-for="(item1, listIndex) in leftComponents" :key="`1_${listIndex}`">
              <div class="components-title">
                <svg-icon icon-class="module" />
                <span>{{ item1.title }}</span>
              </div>
              <draggable
                class="components-draggable"
                :list="item1.list"
                :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                draggable=".components-item"
                :sort="false"
                :clone="cloneComponent"
              >
                <div v-for="(item2, index) in item1.list" :key="`2_${index}`" class="components-item">
                  <div class="components-body" @click="addQueryList(item2)">
                    <svg-icon :icon-class="item2.__config__.tagIcon" />
                    <span>{{ item2.__config__.label }}</span>
                  </div>
                </div>
              </draggable>
            </div>
            <hr />
            <!-- 查询部分 -->
            <div>
              <div class="components-title">
                <svg-icon icon-class="module" />
                <span>查询部分</span>
              </div>
              <draggable class="components-draggable" :list="queryList" :group="{ name: 'componentsGroup' }" draggable=".components-item">
                <div v-for="(item, index) in queryList" :key="`3_${index}`" class="components-item">
                  <div class="components-body" :class="cellHighlight.prop === item.__form__.id ? 'selectModule' : ''" @click="selectedEvent(item)">
                    <svg-icon :icon-class="item.__config__.tagIcon" />
                    <span>{{ item.__form__.label }}</span>
                  </div>
                </div>
              </draggable>
            </div>
            <!-- 表格部分 -->
            <div>
              <div class="components-title">
                <svg-icon icon-class="module" />
                <span>表格部分</span>
              </div>
              <div class="components-body" @click="openJsonDialog()">
                <span>表格属性</span>
              </div>
              <draggable v-if="tableInfo" v-model="tableInfo.dropCol" animation="300">
                <div v-for="(item, index) in tableInfo.dropCol" :key="`4_${index}`" class="components-item">
                  <div
                    class="components-body"
                    :class="cellHighlight.prop === item.id ? 'selectModule' : ''"
                    @click="transformationForm('columnComponents', item)"
                  >
                    <svg-icon icon-class="input" />
                    <span>{{ item.label || item.prop }}</span>
                  </div>
                </div>
              </draggable>
            </div>
            <!-- 分页部分 -->
            <div>
              <div class="components-title">
                <svg-icon icon-class="module" />
                <span>分页部分</span>
              </div>
              <div class="components-draggable">
                <div class="components-body">
                  <span>分页属性</span>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-col>
      <el-col :span="15" style="height: 100%">
        <el-scrollbar style="height: 100%">
          <div class="app-container">
            <!-- 筛选条件 -->
            <div class="filter-container">
              <template v-for="item in queryList">
                <el-input
                  :key="`${item.__config__.type}_${item.__form__.id}`"
                  v-if="item.__config__.type === 'input'"
                  class="filter-item filter-item-input"
                  v-model="item.__form__.value"
                  :placeholder="item.__form__.placeholder"
                  :disabled="item.__form__.disabled"
                  :readonly="item.__form__.readonly"
                  :clearable="item.__form__.clearable"
                />
                <el-select
                  :key="`${item.__config__.type}_${item.__form__.id}`"
                  v-if="item.__config__.type === 'select'"
                  class="filter-item filter-item-input"
                  v-model="item.__form__.value"
                  :placeholder="item.__form__.placeholder"
                  :clearable="item.__form__.clearable"
                >
                  <el-option v-for="item in item.__form__.option" :key="`6_${item.id}`" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <el-date-picker
                  :key="`${item.__config__.type}_${item.__form__.id}`"
                  v-if="item.__config__.type === 'timePicker'"
                  class="filter-item filter-item-input"
                  v-model="item.__form__.value"
                  type="date"
                  :format="item.__form__.format"
                  :value-format="item.__form__.valueFormat"
                  :placeholder="item.__form__.placeholder"
                  :clearable="item.__form__.clearable"
                />
                <el-date-picker
                  :key="`${item.__config__.type}_${item.__form__.id}`"
                  v-if="item.__config__.type === 'timeQuantum'"
                  class="filter-item"
                  v-model="item.__form__.value"
                  type="daterange"
                  :format="item.__form__.format"
                  :value-format="item.__form__.valueFormat"
                  :range-separator="item.__form__.placeholderCenter"
                  :start-placeholder="item.__form__.placeholderStart"
                  :end-placeholder="item.__form__.placeholderEnd"
                  :clearable="item.__form__.clearable"
                  :editable="false"
                />
                <el-button
                  :key="`${item.__config__.type}_${item.__form__.id}`"
                  v-if="item.__config__.type === 'button'"
                  class="filter-item"
                  :icon="item.__form__.icon"
                  :type="item.__form__.type"
                  :disabled="item.__form__.disabled"
                  :circle="item.__form__.circle"
                  >{{ item.__form__.circle ? '' : item.__form__.label }}
                </el-button>
                <br :key="`${item.__config__.type}_${item.__form__.id}`" v-if="item.__config__.type === 'br'" />
                <hr :key="`${item.__config__.type}_${item.__form__.id}`" v-if="item.__config__.type === 'hr'" />
              </template>
            </div>
            <!-- 表格 -->
            <el-table
              v-if="tableInfo"
              :data="tableInfo.tableData"
              :height="tableInfo.height"
              :align="tableInfo.align"
              :border="tableInfo.border"
              :header-cell-style="cellStyle"
              :cell-style="cellStyle"
            >
              <el-table-column
                v-for="(item, index) in tableInfo.dropCol"
                :key="`col_${index}`"
                :prop="item.prop"
                :label="item.label"
                :width="item.width || ''"
                :align="item.align"
                :show-overflow-tooltip="item.showOverflowTooltip"
                :formatter="(a, b, c) => filtering(c, item.timeFilte, item.dictFilte)"
              />
            </el-table>
            <!-- 分页 -->
          </div>
        </el-scrollbar>
      </el-col>
      <el-col :span="5" style="height: 100%">
        <el-form class="el_form" label-width="100px" label-position="right" ref="form" :model="cellHighlight._item">
          <div v-for="(item, index) in cellHighlight._form" :key="`form_${index}`">
            <el-form-item v-if="item.type === 'input'" :label="item.label">
              <el-input
                v-model="cellHighlight._item[item.prop]"
                :disabled="item.disabled || false"
                :readonly="item.readonly || false"
                :placeholder="item.placeholder || ''"
              >
                <el-button
                  v-if="item.button ? true : false"
                  slot="append"
                  @click="dispatchingEvents(item.buttonEvent, { key: item.prop, value: cellHighlight._item[item.prop] })"
                >
                  {{ item.button }}
                </el-button>
              </el-input>
            </el-form-item>
            <el-form-item v-if="item.type === 'textarea'" :label="item.label">
              <el-input style="width: 80%;" v-model="cellHighlight._item[item.prop]" type="textarea" :placeholder="item.placeholder || ''" />
            </el-form-item>
            <el-form-item v-if="item.type === 'select'" :label="item.label">
              <el-select style="width: 80%;" v-model="cellHighlight._item[item.prop]" :placeholder="item.placeholder || ''">
                <el-option v-for="opt in item.options" :key="`${cellHighlight._item.id}_${opt.id}`" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="item.type === 'boole'" :label="item.label">
              <el-switch v-model="cellHighlight._item[item.prop]" />
            </el-form-item>
            <el-form-item v-if="item.type === 'dictionaries'" label-width="10px">
              <span style="font-size: 1.1em;font-weight: 600;">{{ item.label }}</span>
              <template v-for="(opt, index) in cellHighlight._item[item.prop]">
                <el-row :gutter="6" :key="`${opt.key}_${index}`">
                  <el-col :span="10">
                    <el-input v-model="opt.value" placeholder="取值" style="margin-bottom: 1px" />
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="opt.label" placeholder="显示" style="margin-bottom: 1px" />
                  </el-col>
                  <el-col :span="3">
                    <el-button type="danger" icon="el-icon-delete" circle @click="optionDelete(cellHighlight._item[item.prop], opt)" />
                  </el-col>
                </el-row>
              </template>
              <el-button icon="el-icon-circle-plus-outline" type="text" @click="optionAdd(cellHighlight._item[item.prop])">
                添加规则
              </el-button>
            </el-form-item>
            <el-form-item v-if="item.type === 'button'">
              <el-button
                :type="item.style ? item.style.type : ''"
                :icon="item.style ? item.style.icon : ''"
                @click="dispatchingEvents(item.event, cellHighlight._item)"
                >{{ item.label }}
              </el-button>
            </el-form-item>
          </div>
        </el-form>
        <el-button @click="tttt">查看数据</el-button>
        <div v-show="!cellHighlight._form" class="empty_form">
          <span>未选中组件或当前组件无属性设置</span>
        </div>
      </el-col>
    </el-row>
    <!-- 图标选择 -->
    <icons-dialog :visible.sync="iconsVisible" :current="current" @select="setIcon" />
    <json-dialog :dialogVisible.sync="jsonVisible" :p-vue="pVue" />
    <!-- 悬浮按钮 -->
    <div class="suspension">
      <el-button type="primary" icon="el-icon-edit" size="medium" round @click="toHome()">编辑功能</el-button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import draggable from 'vuedraggable'
import IconsDialog from '@/components/table-generator/view/IconsDialog'
import JsonDialog from '@/components/table-generator/view/JsonDialog'
import formList from '@/components/table-generator/js/form'
import {
  queryComponents, // 操作型组件
  layoutComponents, // 布局型组件
  tableComponents // 表格组件
} from '@/components/table-generator/js/config'

var mock = [
  { date: '2016-05-02 14:25', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', type: '1' },
  { date: '2016-05-04 14:25', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄', type: '1' },
  { date: '2016-05-01 14:25', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄', type: '2' },
  { date: '2016-05-03 14:25', name: '王小虎', address: '上海市普陀区金沙江路 1516 弄', type: '0' }
]
export default {
  name: 'Index',
  components: { draggable, IconsDialog, JsonDialog },
  data() {
    return {
      // 事件总线
      pVue: new Vue(),
      drag: false,
      // 左侧组件
      leftComponents: [
        {
          title: '操作型组件',
          list: queryComponents
        },
        {
          title: '布局型组件',
          list: layoutComponents
        }
      ],
      // 查询条件列表
      queryList: [],
      // 表格数据
      tableInfo: {
        dropCol: [], // 数据字段
        tableData: [], // 查询数据
        total: 0 // 总数
      },
      // 表格选中组件
      cellHighlight: {
        type: null, // 选中类型
        prop: null, // 选中id或编码
        _form: null, // 该类型表单
        _item: null // 该类型数据
      },
      // 图标选择
      iconsVisible: false,
      // 已选中图标名称及图标
      currentKey: '',
      current: '',
      // 接口弹窗控制
      jsonVisible: false
    }
  },
  mounted() {
    if (this.pVue) {
      // 生成表格数据
      this.pVue.$on('create-table', data => this.createTable(data))
    }
    this.init()
  },
  methods: {
    // 测试方法
    tttt() {
      console.log(this.queryList, 123)
    },
    /**
     * 【周期】 初始化
     */
    init() {
      this.createTable(mock)
    },
    /**
     * 【封装】 获取唯一ID
     * @returns {string} 过滤结果
     */
    getID() {
      return parseInt(new Date().getMilliseconds() + '' + Math.ceil(Math.random() * 100000)).toString(16)
    },
    /**
     * 【数据操作】 复制组件
     * @returns {string} 深拷贝组件
     */
    cloneComponent(origin) {
      const data = JSON.parse(JSON.stringify(origin))
      data.__form__.id = this.getID()
      return data
    },
    /**
     * 【数据操作】 通过点击 增加筛选条件
     */
    addQueryList(item) {
      const __form__ = {
        ...item.__form__,
        id: this.getID()
      }
      // 对象深拷贝
      const data = Object.assign({}, item, { __form__ })
      this.queryList.push(data)
    },
    /**
     * 【数据操作】 选中组件
     */
    selectedEvent(item) {
      this.cellHighlight = {
        type: item.__config__.type,
        prop: item.__form__.id,
        _form: formList[item.__config__.type],
        _item: item.__form__
      }
    },
    /**
     * 【数据操作】 选中单元格
     */
    transformationForm(type, item) {
      if (this.cellHighlight.type === type && this.cellHighlight.prop === item.id) {
        this.cellHighlight = {
          type: null, // 选中类型
          prop: null, // 选中id或编码
          _form: null, // 该类型表单
          _item: null // 该类型数据
        }
        return
      }
      this.cellHighlight = {
        type,
        prop: item.id,
        property: item.prop,
        _form: formList[type],
        _item: item
      }
    },
    /**
     * 【数据操作】 增加字典
     */
    optionAdd(option) {
      option.push({
        id: this.getID(),
        value: '',
        label: ''
      })
    },
    /**
     * 【数据操作】 删除字典
     */
    optionDelete(option, opt) {
      this.$utils.remove(option, e => e === opt)
    },
    /**
     * 【表单操作】 表单按钮事件分发
     * @param event 事件名称
     * @param item 事件参数
     */
    dispatchingEvents(event, item) {
      if (this[event]) {
        this[event](item)
      } else {
        console.error('【' + event + '方法不存在】')
        console.log('【参数】', item)
      }
    },
    /**
     * 【表格监听】 数据过滤器
     * @param value 需要过滤字段
     * @param timeFilte 时间过滤格式
     * @param dictFilte 字典过滤格式
     * @returns {string} 过滤结果
     */
    filtering(value, timeFilte = '', dictFilte = []) {
      if (typeof value === 'string') {
        // 时间过滤
        if (timeFilte) {
          if (!new Date(value).getTime()) {
            return '时间格式不标准'
          } else {
            return this.$moment(value).format(timeFilte)
          }
        }
        // 字典过滤
        if (dictFilte.length) {
          const boo = dictFilte.find(e => e.value === value)
          if (boo) return boo.label
        }
        return value
      } else {
        return '不是字符串'
      }
    },
    /**
     * 【表格监听】 表格样式
     * @param column 字段名
     */
    cellStyle({ column }) {
      if (this.cellHighlight.type === 'columnComponents') {
        if (this.cellHighlight.property === column.property) {
          return {
            'background-color': '#67C23A',
            color: '#ffffff'
          }
        }
      }
    },
    /**
     * 被分发--删除当前字段
     */
    deleteCol(item) {
      this.$utils.remove(this.tableInfo.dropCol, e => e.id === item.id)
      // 右侧表单清空
      this.cellHighlight = {
        type: null,
        prop: null,
        _form: null,
        _item: null
      }
    },
    /**
     * 分发事件 查询条件删除
     */
    deleteHis(item) {
      this.$utils.remove(this.queryList, e => e.__form__.id === item.id)
      // 右侧表单清空
      this.cellHighlight = {
        type: null,
        prop: null,
        _form: null,
        _item: null
      }
    },
    /**
     * 【属性操作】 图标选中
     */
    setIcon(val) {
      this.cellHighlight._item[this.currentKey] = val
      // 修改完后清除中间变量
      this.currentKey = ''
      this.current = ''
    },
    /**
     * 【属性操作】 切换图标
     * @param item
     */
    openIconsDialog(item) {
      // 创建中间变量保存
      this.currentKey = item.key
      this.current = item.value
      this.iconsVisible = true
    },
    /**
     * 【属性】 打开获取接口数据页面
     */
    openJsonDialog() {
      this.jsonVisible = true
      this.$nextTick(() => {
        this.pVue.$emit('jsonDialog-init', this.tableInfo.tableData)
      })
    },
    /**
     * 【生成】 根据新数据生成表格
     * @param table
     */
    createTable(tableData) {
      const boo = this.$getsub(tableData, 0)
      if (boo) {
        let dropCol = []
        for (let key in boo) {
          dropCol.push(
            Object.assign({}, tableComponents[0].__form__, {
              id: this.getID(),
              prop: key,
              label: key
            })
          )
        }
        this.tableInfo = {
          dropCol,
          tableData,
          total: 0
        }
        console.log('表格创建完成=>\n', this.tableInfo)
      } else {
        this.$log(0, '解析失败')
      }
    },
    /**
     * 按钮 去编辑功能
     */
    toHome() {
      this.$router.push('/HOME')
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../components/table-generator/css/home';

.page {
  width: 100%;
  height: 100%;

  /* 右侧表单 */
  .el_form {
    padding-top: 15px;
    padding-right: 15px;
  }

  /* 空表单 */
  .empty_form {
    width: 100%;
    height: 80%;
    display: flex;
    align-items: center;
    justify-content: center;

    span {
      color: #ccc2f2;
    }
  }

  // 左侧模块选中
  .selectModule {
    border: 1px dashed #67c23a;
    color: #67c23a;
    svg {
      color: #67c23a !important;
    }
  }

  // 悬浮按钮
  .suspension {
    position: fixed;
    bottom: 20px;
    right: 20px;
  }
}
</style>
